<route lang="json5">
	{
	layout: 'default',
	style: {
	navigationBarTitleText: '实验报告详情',
	enablePullDownRefresh: true,
	navigationStyle: 'custom'
	}
	}
</route>

<template>
	<page-meta :root-font-size="setting.rootFontSize"></page-meta>
	<view style="background-color: #e3e3e3">
		<view style="position: sticky; top: 0; z-index: 9999">
			<wd-navbar title="实验报告评审" :bordered="false" safeAreaInsetTop>
				<template #left>
					<wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
				</template>
			</wd-navbar>
		</view>
		<th-card title="基础信息">
			<th-form>
				<th-form-item label="项目名称" v-if="form.petitionName">
					<text class="text">{{ form.petitionName }}</text>
				</th-form-item>
				<th-form-item label="产品名称">
					<wd-textarea disabled type="textarea" auto-height v-model="form.invName" clearable style="width: 100%"
						no-border class="diabledStyle" placeholder="产品名称">
					</wd-textarea>
					<!-- <text class="text">{{ form.invName }}</text> -->
				</th-form-item>
				<th-form-item label="产品规格">
					<wd-textarea disabled type="textarea" auto-height v-model="form.invStd" clearable style="width: 100%"
						no-border class="diabledStyle" placeholder="产品规格">
					</wd-textarea>
					<!-- <text class="text">{{ form.invStd }}</text> -->
				</th-form-item>
				<th-form-item label="实验目的">
					<wd-textarea v-model="form.purpose" disabled placeholder=" " style="width: 100%" no-border
						class="diabledStyle">
					</wd-textarea>
					<!-- <text class="text">{{ form.purpose }}</text> -->
				</th-form-item>
				<th-form-item label="任务负责人">
					<view>
						<text class="text" v-for="(item, index) in form.projectHeadName" :key="index">
							{{ index > 0 ? '，' : '' }}{{ item.userName }}
						</text>
					</view>
				</th-form-item>
				<template v-if="showMoreDemand">
					<th-form-item label="任务成员">
						<view>
							<text class="text" v-for="(item, index) in form.rdProjectUserEntity" :key="index">
								{{ index > 0 ? '，' : '' }}{{ item.userName }}
							</text>
						</view>
					</th-form-item>
					<th-form-item label="报告编码">
						<text class="text">{{ form.ccode }}</text>
					</th-form-item>
					<th-form-item label="报告日期">
						<text class="text">{{ form.ddate }}</text>
					</th-form-item>
					<th-form-item label="任务编码">
						<text class="text">{{ form.projectCode }}</text>
					</th-form-item>
					<th-form-item label="需求描述">
						<wd-textarea v-model="form.description" disabled placeholder=" " style="width: 100%;" no-border
							class="diabledStyle">
						</wd-textarea>
						<!-- <text class="text">{{ form.description }}</text> -->
					</th-form-item>

					<th-form-item label="反应方程式">
						<text class="text">
							<image class="craft-row-img" :src="form.reactEquation" mode="scaleToFill"
								@click="previewFileHandle(form.reactEquation)" />
						</text>
					</th-form-item>
					<view style="width:100%;">
						<view class="viewLabel"><text>反应装置</text></view>
						<view class="table-container">
							<table class="analysis-table">
								<tbody>
									<tr>
										<th>反应装置</th>
										<th>用料规格</th>
										<th>最大搅拌量</th>
										<th>最小搅拌量</th>
										<th>单位</th>
									</tr>
									<tr align="center" v-for="(  item, index  ) in form.deviceList" :key="index">
										<td>{{ item.name }}</td>
										<td>{{ item.capacity }}</td>
										<td>{{ item.maxValue }}</td>
										<td>{{ item.minValue }}</td>
										<td>{{ item.unit }}</td>
									</tr>
								</tbody>
							</table>
						</view>
					</view>
				</template>

				<view class="exportModel" @click="showMoreDemand = !showMoreDemand">
					<text>{{ showMoreDemand ? '收起' : '展开' }}</text>
				</view>
			</th-form>

			<!-- <th-form labelWidth="100px">
				<th-form-item label="反应装置" class="viewTable">
					<view class="table-container">
						<table class="analysis-table">
							<tbody>
								<tr>
									<th>反应装置</th>
									<th>用料规格</th>
									<th>最大搅拌量</th>
									<th>最小搅拌量</th>
									<th>单位</th>
								</tr>
								<tr align="center" v-for="(  item, index  ) in form.deviceList" :key="index">
									<td>{{ item.name }}</td>
									<td>{{ item.capacity }}</td>
									<td>{{ item.maxValue }}</td>
									<td>{{ item.minValue }}</td>
									<td>{{ item.unit }}</td>
								</tr>
							</tbody>
						</table>
					</view>
				</th-form-item>
			</th-form> -->
		</th-card>
		<th-card title="需求指标" v-if="form.rdDemandStandardEntity && form.rdDemandStandardEntity.length">
			<view class="table-container">
				<table class="analysis-table">
					<tbody>
						<tr>
							<th>检验指标名称</th>
							<th>U8指标</th>
							<th>客户指标</th>
							<th>检测值</th>
							<th>描述</th>
						</tr>
						<tr align="center" v-for="(  item, index  ) in form.rdDemandStandardEntity" :key="index">
							<td>{{ item.standardName }}</td>
							<td>{{ item.standardValue }}</td>
							<td>{{ item.standardValuePm }}</td>
							<td>{{ item.checkValue }}</td>
							<td>{{ item.standardDesc }}</td>
						</tr>
					</tbody>
				</table>
			</view>
		</th-card>
		<th-card title="用料及配比">
			<view class="table-container">
				<table class="analysis-table">
					<tbody>
						<tr>
							<th style="width: 320rpx; min-width: 9.5rem">用料名称</th>
							<th style="width: 280rpx; min-width: 380rpx">用料规格</th>
							<th style="width: 280rpx; min-width: 180rpx">密度</th>
							<th style="width: 280rpx; min-width: 180rpx">占比（%）</th>
							<th style="width: 280rpx; min-width: 480rpx">范围</th>
							<th style="width: 280rpx; min-width: 280rpx">计划用量</th>
							<th style="width: 280rpx; min-width: 280rpx">实际用量</th>
							<th style="width: 320rpx; min-width: 180rpx">单位</th>
						</tr>
						<tr align="center" v-for="(  item, index  ) in materialList" :key="index">
							<td>{{ item.invName }}</td>
							<td>{{ item.invStd }}</td>
							<td>{{ item.density }}</td>
							<td>{{ item.proportion }}</td>
							<td>
								<text>{{ minPlanDosage(item.density, item.proportion, form.deviceList &&
									form.deviceList[0].minValue) }}</text>
								~
								<text>{{ maxPlanDosage(item.density, item.proportion, form.deviceList &&
									form.deviceList[0].maxValue) }}</text>
							</td>
							<td>{{ item.planNum }}</td>
							<td>{{ item.realNum }}</td>
							<td>{{ item.unit }}</td>
						</tr>
					</tbody>
				</table>
			</view>
		</th-card>
		<th-card title="用料产出" v-if="recordOutList && recordOutList.length">
			<view class="table-container">
				<table class="analysis-table">
					<tbody>
						<tr>
							<th>物料名称</th>
							<th>物料规格</th>
							<th>数量</th>
							<th>单位</th>
						</tr>
						<tr align="center" v-for="(  item, index  ) in recordOutList" :key="index">
							<td>{{ item.invName }}</td>
							<td>{{ item.invStd }}</td>
							<td>{{ item.dosage }}</td>
							<td>{{ item.unit }}</td>
						</tr>
					</tbody>
				</table>
			</view>
		</th-card>
		<th-card :title="!switchAction ? '实验过程记录' : '工艺流程'">
			<template v-slot:titleRight>
				<text @click="() => switchAction = !switchAction">
					<wd-icon name="translate-bold" size="22px"></wd-icon>
				</text>
			</template>
			<view v-show="!switchAction">
				<ExperimnetStepTablePreview :materialList="tableStepList" :record-id="form.pid" />
			</view>
			<view v-show="switchAction">
				<ExperimnetStepPreview :materialList="form.stepList" mode="record"
					@switchChange="switchAction = !switchAction" />
			</view>
			<!-- <ExperimnetStepPreview :materialList="form.stepList" mode="record" /> -->
		</th-card>
		<th-card id="reportView5" title="检验结论">
			<view class="table-container">
				<scroll-view scroll-x scroll-y class="th-table">
					<table class="analysis-table" v-if="middleCheckData.length">
						<thead class="sticky_top">
							<tr>
								<th colspan="9">中控检验报告</th>
							</tr>
							<tr>
								<th>工序</th>
								<th>报检次序</th>
								<th>取样位置</th>
								<th style="white-space: nowrap;">取样时机描述</th>
								<th>取样时机</th>
								<th>分析手段</th>
								<th>指标名称</th>
								<th>实测值</th>
								<th>报告</th>
							</tr>
						</thead>
						<tr align="center" v-for="(item, index) in middleCheckData" :key="index">
							<td>{{ item.processName }}</td>
							<td>{{ item.rowNum }}</td>
							<td>{{ item.position }}</td>
							<td>{{ item.sampleDesc }}</td>
							<td style="white-space: nowrap;">{{ item.sampleTime }}</td>
							<td>{{ item.analysisName }}</td>
							<td>
								<view style="width:100px">{{ item.itemName }}</view>
							</td>
							<td>{{ item.itemValue }}</td>
							<td>
								<block v-if="item.attachmentsEntities && item.attachmentsEntities.length">
									<view v-for="file in item.attachmentsEntities" :key="file.id"
										style="min-width:150px;color:#2e5cf6" @click="readFile(item, file.url)">
										{{ file.name }}
									</view>
								</block>
								<text style="color:#ccc" v-else>无报告</text>
							</td>
						</tr>
						<!-- </tbody> -->
					</table>
				</scroll-view>
			</view>
			<view class="table-container">
				<scroll-view scroll-x scroll-y class="th-table">
					<table class="analysis-table" v-if="finalCheckData.length" style="margin-top:15rpx;">
						<thead class="sticky_top">
							<tr>
								<th colspan="9">终检检验报告</th>
							</tr>
							<tr>
								<th>工序</th>
								<th>报检次序</th>
								<th>取样位置</th>
								<th style="white-space: nowrap;">取样时机描述</th>
								<th>取样时机</th>
								<th>分析手段</th>
								<th>指标名称</th>
								<th>实测值</th>
								<th>报告</th>
							</tr>
						</thead>
						<tbody>

							<tr align="center" v-for="(item, index) in finalCheckData" :key="index">
								<td>{{ item.processName }}</td>
								<td>{{ item.rowNum }}</td>
								<td>{{ item.position }}</td>
								<td>{{ item.sampleDesc }}</td>
								<td style="white-space: nowrap;">{{ item.sampleTime }}</td>
								<td>{{ item.analysisName }}</td>
								<td>
									<view style="width:100px">{{ item.itemName }}</view>
								</td>
								<td>{{ item.itemValue }}</td>
								<td>
									<block v-if="item.attachmentsEntities && item.attachmentsEntities.length">
										<view v-for="file in item.attachmentsEntities" :key="file.id"
											style="min-width:150px;color:#2e5cf6" @click="readFile(item, file.url)">
											{{ file.name }}
										</view>
									</block>
									<text style="color:#ccc" v-else>无报告</text>
								</td>
							</tr>
						</tbody>
					</table>
				</scroll-view>
			</view>
		</th-card>
		<th-card title="报告图表">
			<view class="chart-container" v-for="(chart, index) in chartList" :key="index">
				<echarts :option="chart.chartOptions" style="height: 400px"></echarts>
			</view>
		</th-card>
		<th-card title="附件">
			<view class="table-container">
				<table class="analysis-table">
					<tbody>
						<tr>
							<th>附件名称</th>
							<th>附件描述</th>
						</tr>
						<block v-if="fileList.length">
							<tr align="center" v-for="(item, index) in fileList" :key="index"
								@click="previewFile(item.fileUrl)">
								<td>{{ item.fileName }}</td>
								<td>{{ item.remark }}</td>
							</tr>
						</block>

						<block v-else>
							<tr align="center">
								<td :colspan="2">暂无数据</td>
							</tr>
						</block>
					</tbody>
				</table>
			</view>
		</th-card>
		<th-card title="实验分析评审结论">
			<th-form>
				<th-form-item label="是否结题">
					<text>{{ form.completeFlag ? '是' : '否' }}</text>
				</th-form-item>
				<th-form-item label="评审结果">
					<wd-picker v-model="form.rdFlag" disabled :columns="rdFlags" style="background-color: transparent;"
						class="diabledStyle" placeholder=" " />
				</th-form-item>
				<!-- <th-form-item label="任务类型" v-if="form.rdFlag === 3">
					<wd-picker v-model="form.typeCode" disabled :columns="taskType" style="background-color: transparent;"
						class="diabledStyle" />
				</th-form-item> -->
				<th-form-item label="回复">
					<wd-textarea type="textarea" auto-height v-model="form.reply" placeholder=" " style="width: 100%"
						disabled class="diabledStyle"></wd-textarea>
				</th-form-item>
				<!-- <th-form-item label="采购新设备">
					<wd-radio-group v-model="form.deviceFlag" inline disabled>
						<wd-radio :value="0">否</wd-radio>
						<wd-radio :value="1">是</wd-radio>
					</wd-radio-group>
				</th-form-item> -->
				<th-form-item label="结论">
					<wd-textarea auto-height v-model="form.conclusion" placeholder=" " style="width: 100%" disabled
						class="diabledStyle"></wd-textarea>
				</th-form-item>
				<th-form-item label="需求反馈方式">
					<wd-picker v-model="form.replyFlag" :columns="replyFlags" disabled
						style="background-color: transparent;padding:0;" class="diabledStyle" placeholder=" " />
				</th-form-item>
				<!-- <th-form-item label="评审意见">
					<wd-textarea auto-height v-model="form.advise" placeholder=" " style="width: 100%" clearable
						:disabled="[2, 3, 4].includes(form.reviewStatus) || cusPerson != '2006031401'" class="diabledStyle"
						@blur="handleSave"></wd-textarea>
				</th-form-item> -->
			</th-form>
			<view v-if="form.completeFlag == 1 && form.status == 2 && form.compoundFlag != 1">
				<view class="viewLabel"><text>评审附件</text></view>
				<view class="table-container">
					<table class="analysis-table">
						<tbody>
							<tr>
								<th>附件名称</th>
								<th>附件描述</th>
							</tr>
							<block v-if="reviewFileList.length">
								<tr align="center" v-for="(item, index) in reviewFileList" :key="index"
									@click="previewFile(item.fileUrl)">
									<td>{{ item.fileName }}</td>
									<td>{{ item.remark }}</td>
								</tr>
							</block>
							<block v-else>
								<tr align="center">
									<td :colspan="2">暂无数据</td>
								</tr>
							</block>
						</tbody>
					</table>
				</view>
			</view>
		</th-card>
		<!-- <th-card title="结题附件" v-if="form.completeFlag == 1">
			<view class="table-container">
				<table class="analysis-table">
					<tbody>
						<tr>
							<th>附件名称</th>
							<th>附件描述</th>
						</tr>
						<block v-if="reviewFileList.length">
							<tr align="center" v-for="(item, index) in reviewFileList" :key="index"
								@click="previewFile(item.fileUrl)">
								<td>{{ item.fileName }}</td>
								<td>{{ item.remark }}</td>
							</tr>
						</block>
						<block v-else>
							<tr align="center">
								<td :colspan="2">暂无数据</td>
							</tr>
						</block>
					</tbody>
				</table>
			</view>
		</th-card> -->
		<th-card title="评审意见">
			<view class="table-container">
				<table class="analysis-table">
					<tbody>
						<tr>
							<th>评审人</th>
							<th>评审意见</th>
						</tr>
						<block v-if="form.adviseList.length">
							<tr align="center" v-for="(item, index) in form.adviseList" :key="index">
								<td>{{ item.username }}</td>
								<td>{{ item.advise }}</td>
							</tr>
						</block>
						<block v-else>
							<tr align="center">
								<td :colspan="2">暂无数据</td>
							</tr>
						</block>
					</tbody>
				</table>
			</view>
			<view v-if="includeUserListVisible">
				<wd-textarea show-word-limit v-model="form.advise" placeholder=" " clearable :maxlength="120"
					:disabled="[2, 3, 4].includes(form.reviewStatus)" class="diabledStyle"></wd-textarea>

				<view class="btn_group" style="width: 100%" v-if="![2, 3, 4].includes(form.reviewStatus)">
					<view class="btn primary" @click="handleSave">
						<image src="../../../static/save.png" class="btn-icon"></image>
						保存
					</view>
				</view>
			</view>
		</th-card>
		<th-card title="评审人员签字">
			<th-form>
				<th-form-item v-for="item in form.userList.filter(item => item.documentsPostName != '参会人员')"
					:label="item.documentsPostName">
					<wd-img :width="200" :height="100" :src="item.userUrl" @click="preview(item.userUrl)" />
				</th-form-item>
			</th-form>
			<th-form>
				<th-form-item v-for="item in form.userList.filter(prop => prop.documentsPostName == '参会人员' && prop.userUrl)"
					:label="item.documentsPostName">
					<wd-img :width="200" :height="100" :src="item.userUrl" @click="preview(item.userUrl)" />
				</th-form-item>
			</th-form>
		</th-card>
		<view v-if="showSign" class="sign-main bg-white" @click="sign">签字</view>
	</view>
	<!-- <view class="flow-btn-fixed" v-if="form.status != 2">
		<view class="btn_group" style="width: 100%">
			<view class="btn primary" @click="handleSave">保存</view>
		</view>
	</view> -->
	<wd-action-sheet v-model="showAction" title="" @close="closeSign" @click-modal="closeSign">
		<view class="sign-main-show">
			<text class="sign-main-show-title">签字</text>
			<view class="sign-main-show-line">
				<wd-img :width="200" :height="100" :src="signature" @click="signThis" />
			</view>
			<!-- <view class="sign-main-show-btn" @click="signThis">使用该签字</view> -->
			<view class="sign-main-show-btn" @click="signReset">重新签字</view>
		</view>
	</wd-action-sheet>
</template>

<script lang="ts" setup>
import { request } from '@/utils/request';
import echarts from '@/components/echarts.vue';
import { useSetting } from '@/stores/setting';
import { reportInfo } from '@/service/pm-assay';
import { getPersonByPersonCode, uploadSignature } from '@/service/pm-task';
import { getObj, updateByIdEvery, putObj, getSchemeInfoByRecord, getDosageByRecord, getExperimentRecord, getRdTaskDetail, getQcMiddleReport } from '@/service/pm-report';
import { getPageByTask, resultByRecords } from '@/service/pm-record';
// import { formatByDayjs } from '@/utils/util';

import { useUserStore } from '@/stores/user';
import { pieOption, lineOption, barOption } from './echartType';
// import { maxPlanDosage, minPlanDosage } from '../experiment/utils/index'

import ExperimnetStepPreview from '../experiment/components/ExperimnetStepPreview.vue'
import ExperimnetStepTablePreview from './components/ExperimnetStepTablePreview.vue';

const setting = useSetting();
const userStore = useUserStore();
const showSign = ref(false);
const signature = ref('');
const userInfo = ref({});
const isChiefEngineer = ref('');
const isDeputyChiefEngineer = ref('');
const isLaboratoryLeader = ref('');
const switchAction = ref(false)
const showAction = ref(false);
const reportResultList = ref([])
const materialList = ref([])
interface TypeOption {
	label?: string;
	code?: string;
	type?: number;
}
const typeList: Array<TypeOption> = [
	{
		label: '折线图',
		code: 'line',
		type: 0,
	},
	{
		label: '柱状图',
		code: 'bar',
		type: 1,
	},
	{
		label: '饼图',
		code: 'pie',
		type: 2,
	},
];

const replyFlags = ref([
	{
		label: '总经理确认后反馈',
		value: 2
	},
	{
		label: '直接反馈',
		value: 1
	},
	{
		label: '不反馈',
		value: 0
	},
])

const rdFlags = ref([
	{
		label: '通过',
		value: 1
	},
	{
		label: '修正实验方案',
		value: 0
	},
	{
		label: '重新实验',
		value: 2
	},
	{
		label: '调整合成路径',
		value: 3
	},
	{
		label: '终止任务',
		value: 4
	},
])

const taskType = ref([
	{
		label: '来样检验',
		value: 2
	},
	{
		label: '新品资料收集合成路线',
		value: 3
	},
	{
		label: '直接取样检测',
		value: 30
	},
	{
		label: '调查问卷',
		value: 4
	},
	{
		label: '复配稀释',
		value: 6
	},
	{
		label: '其他',
		value: 9
	},
	{
		label: '研发任务',
		value: 10
	},
])
const showMoreDemand = ref(false)
const middleCheckData = ref([])
const finalCheckData = ref([])
// 提交表单数据
const form = reactive({
	id: null,
	technologyId: null,
	demandDate: null,
	personName: null,
	demandType: null,
	deptHead: null,
	deptCode: null,
	applicationType: null,
	samplesNum: null,
	demandDesc: null,
	sampleCoding: null,
	askCompleteTime: null,
	taskCode: null,
	userCode: null,
	invName: null,
	invDemand: null,
	sampleFlag: null,
	demandCode: null,
	cusName: null,
	personCode: null,
	deptHeadCode: null,
	cusFlag: '0',
	demandResult: null,
	completeTime: null,
	technologyHead: null,
	remark: null,
	technologyHeadCode: null,
	taskId: null,
	processInstanceId: null,
	invStd: null,
	sampleCode: null,
	sampleBatch: null,
	deptName: null,
	rdFlag: null,
	chiefEngineer: null,
	deputyChiefEngineer: null,
	status: null,
	sampleFlagName: null,
	deputyChiefEngineerUrl: null,
	laboratoryLeaderUrl: null,
	chiefEngineerUrl: null,
	sampleUnit: null,
	cusCode: null,
	projectCode: null,
	projectName: null,
	rdProjectUserEntity: null,
	projectHead: null,
	completionTime: null,
	technologyHeadName: null,
	rdInformationDTO: [],
	rdCraftEntity: [],
	rdSampleAnalysisEntity: [],
	rdPlan: null,
	conclusion: '',
	sampleReviewConclusion: null,
	requirements: null,
	projectHeadName: null,
	rdDemandStandardEntity: [],
	deviceList: [],
	stepList: [],
	userList: [],
	adviseList: []
});


const technologyName = ref('')
const chartList = shallowRef([]);
const fileList = ref([])
const reviewFileList = ref([])
const recordOutList = ref([])


const includeUserListVisible = computed(() => {
	return form.userList.some(item => item.userCode == cusPerson)
})

/**
 * 工艺路线列表
 */
const craftList = ref([]);


watch(
	() => craftList.value,
	(val) => {
		const technology = val && val.find(item => item.id == form.technologyId)
		technologyName.value = technology ? technology.craftName : '';
	},
	{
		immediate: true,
		deep: true,
	}
)

const userInfos = userStore.userInfos;
const cusPerson = userInfos.user.username;


const init = (params) => {
	uni.$off('pm-requirement-sign');
	uni.showLoading();
	getObj(params)
		.then((res) => {
			res.data.deviceList = res.data.equipmenList || [];
			Object.assign(form, res.data);

			fileList.value = res.data.fileList || []
			reviewFileList.value = res.data.reviewFileList || []
			renderChart(res.data.chartList);

			const user = res.data.userList.find(item => item.userCode == cusPerson)
			showSign.value = user ? true : false;

			const createBy = res.data.adviseList.find(item => item.createBy == cusPerson)
			form.advise = createBy ? createBy.advise : null;


			getBjReportResultList(res.data.checkReportId)

			addInit(res.data.pid);
		})
		.finally(() => {
			uni.stopPullDownRefresh();
			uni.hideLoading();
		});
	// checkPost();
};

const addInit = (id) => {
	getDosageByRecordList(id);
	getSchemeInfoByRecord(id).then((res) => {
		if (res.code === 0) {
			form.purpose = res.data.purpose;

			if (res.data.taskId) {
				getProjectInfo({ id: res.data.taskId, recordId: id });
			}
		}
	});

	getExperimentRecord(id)
		.then((res) => {
			if (res.code === 0) {
				form.stepList = res.data.stepList.map(item => {
					if (item.processName === '中控') {
						item.sampletimeList = []
						item.checkList = []
						item.paramList && item.paramList.map(v => {
							if (v.mcFlag == 1) {
								item.sampletimeList.push(v)
							} else {
								item.checkList.push({
									analysisId: v.analysisId,
									analysisName: v.analysisName,
									itemName: v.paramName,
								})
							}
						})
					}

					return item;
				});

				recordOutList.value = res.data.dosageList?.map(item => { item.recallFlag = res.data.recallFlag; return item }).filter((item) => item.type) || []
				getProcessPageByTask(res.data.id);

				// getBjReportResultList(res.data.id)
			}
		})

	// 检验结论
	getResultByRecords(id);
	// getStepTable(id)
};

/**
 * 实验记录查看
 */
const tableStepList = ref([])
const getStepTable = async (record) => {
	if (!record) return
	try {
		const { data } = await request({
			url: `/pm/experimentRecord/stepTable/${record}`,
			method: 'get',
		});

		tableStepList.value = data

	} catch (error) {
		console.log(error);
		// options.onError(error as any);
	}
}

const isNotNum = (val: string | null | number): boolean => {
	if (typeof val === 'string' && !isNaN(Number(val))) {
		return val.indexOf('.') < 0 && val.indexOf('0') == 0;
	} else {
		return isNaN(Number(val));
	}
};

const transferAndToFixed = (num, length = 0) => {
	const str = num.toFixed(length).toString();
	const reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(\d{3})+$)/g;
	return str.replace(reg, '$1,');
};

const maxPlanDosage = (density: number, proportion: number, maxValue: number) => {
	if (isNotNum(density)) return 0;
	if (isNotNum(maxValue)) return 0;
	if (isNotNum(proportion)) return 0;

	let maxNum = 0;
	//密度（g/ml） * 占比 * 最大搅拌量（ml）
	maxNum = transferAndToFixed(Number(density), 4) * transferAndToFixed(Number(proportion), 4) * transferAndToFixed(Number(maxValue), 4)
	return unifyNumber(transferAndToFixed(maxNum / 100, 4))
}

const minPlanDosage = (density: number, proportion: number, minValue: number) => {

	if (isNotNum(density)) return 0;
	if (isNotNum(minValue)) return 0;
	if (isNotNum(proportion)) return 0;
	let minNum = 0;
	//密度（g/ml） *  占比 * 最小搅拌量（ml）
	minNum = transferAndToFixed(Number(density), 4) * transferAndToFixed(Number(proportion), 4) * transferAndToFixed(Number(minValue), 4)
	return unifyNumber(transferAndToFixed(minNum / 100, 4))
}



const unifyNumber = (num, len = 6) => {
	if (num === '') return ''

	let handleNum = parseFloat(num)
	let isToFixed = handleNum.toString().includes('.') && handleNum.toString().split('.')[1].length > len
	if (isToFixed) {
		return handleNum.toFixed(len)
	} else {
		return handleNum
	}
}

const getDosageByRecordList = (recordId) => {
	getDosageByRecord(recordId)
		.then((res) => {
			if (res.code === 0) {
				if (!res.data) return;
				materialList.value = res.data.map(item => {
					if (item.planNum) {
						item.planNum = unifyNumber(item.planNum,4)
					}
					if (item.realNum) {
						item.realNum = unifyNumber(item.realNum,4)
					}
					return item
				});
			}
		})
};

const getProcessPageByTask = function (id: string) {
	getPageByTask({ pid: id, size: 999 })
		.then((res) => {
			if (res.code === 0) {
				if (form.stepList) {
					form.stepList.map((item) => {
						if (item.putIntoFlag && !item.dosageList?.length) {
							item.dosageList = [{ invName: null, unit: null }];
						}
						item.undraggable = true;

						// if (item.processName === '终检') {
						// 	const zj = res.data.records.find(item => item.type === 1)
						// 	if (zj) {
						// 		item.bgId = zj.id
						// 		item.pid = zj.pid
						// 	}

						// }

						item.inspectionList = res.data.records.filter((v) => v.pid === item.id && v.id) || [];
					});
					form.stepList = form.stepList;
				}
			}
		})
		.catch((err) => {
			console.log(err);
			message.error(err.msg || err.message || '获取工序报检信息失败');
		});
};

const getProjectInfo = function (params) {
	getRdTaskDetail(params).then((res) => {
		if (res.code === 0) {
			form.projectHeadName = res.data.rdProjectUserEntity.filter(item => item.userType == 2) || [];
			// form.technologyHeadName = res.data.rdProjectUserEntity.filter(item => item.userType == 2) || [];
			form.rdProjectUserEntity = res.data.rdProjectUserEntity.filter(item => item.userType == 0) || [];
			// form.deviceList = res.data.equipmenList && res.data.equipmenList || [];
			craftList.value = res.data.rdCraftEntity.filter((item) => item.isUse) || [];
			form.rdDemandStandardEntity = res.data.rdDemandStandardEntity || []
			form.petitionName = res.data.petitionName


			if (form.rdDemandStandardEntity != null && form.rdDemandStandardEntity.length > 0) {
				resultByRecords(params).then((res) => {
					if (res.code === 0) {
						if (res.data && res.data.length > 0) {
							finalCheckData.value = res.data.filter((item) => item.type == 1)
							// state.finalCheckTableData = finalCheckData.value;
							console.log("需求指标" + form.rdDemandStandardEntity)
							if (form.rdDemandStandardEntity != null && form.rdDemandStandardEntity.length > 0) {
								form.rdDemandStandardEntity.forEach((item) => {
									let values = finalCheckData.value.filter(check => item.standardName == check.itemName);
									if (values != null && values.length > 0) {
										item.checkValue = values[values.length - 1].itemValue
									}
								})
							}
						}
					}
				})
			}
			// form.projectHeadName = res.data.projectHeadName;
			// form.technologyHead = res.data.technologyHead;
			// form.technologyHeadName = res.data.technologyHeadName;
			// form.rdProjectUserEntity = res.data.rdProjectUserEntity;
		}
	});
};

//请求中控检验数据
const getResultByRecords = (recordId: string) => {
	resultByRecords({ recordId })
		.then((res) => {
			if (res.code === 0) {
				if (res.data && res.data.length > 0) {
					middleCheckData.value = res.data.filter((item) => item.type == 0)
					finalCheckData.value = res.data.filter((item) => item.type == 1)
				}
			}
		})
		.catch((error) => {
			const err = error.msg || error.error || error;
		});
}

// 渲染图表数据
const renderChart = (list) => {
	if (!list || !list.length) return;
	const arr = list.map((item) => {
		let styleObj = {
			xDateLine: false,
			yDateLine: false,
			line: {
				smooth: false,
				disabled: true,
			},
			bar: {
				barWidth: null,
				barGap: 30,
				disabled: true,
			},
			pie: {
				centerLeft: 50,
				centerTop: 50,
				innerCircle: 40,
				outerCircle: 70,
			},
		};
		item.paramList.forEach((p: { styleList: any[] }) => {
			p.styleList &&
				p.styleList.forEach((i: { style: string }) => {
					if (i.style) {
						const style = JSON.parse(i.style);
						styleObj = {
							...styleObj,
							...style,
						};
					}
				});
			item.style = styleObj;
		});
		return item;
	});

	initEChart(arr);
};

const initEChart = function (list) {
	chartList.value = list.map((item, index) => {
		const chartOptions = JSON.parse(JSON.stringify(defaultOption(item)));
		chartOptions.id = 'echarts' + index;
		return { chartOptions };
	});
};

/**
 * 获取echart图表类型
 */
const getEChartType = (type) => {
	const eType = typeList.find((item) => item.type === type);
	if (eType) return eType;
};

function defaultOption(params) {
	let option = {};
	const echartOption = getEChartType(params.type);
	switch (echartOption.code) {
		case 'line':
			option = lineECharts(params);
			break;
		case 'bar':
			option = barECharts(params);
			break;
		case 'pie':
			option = pieECharts(params);
			break;

		default:
			break;
	}
	return {
		title: {
			top: 0,
			text: params.chartName,
			left: 'center',
		},
		toolbox: {
			feature: {
				magicType: {
					show: false,
					type: ['stack', 'tiled'],
				},
				saveAsImage: {},
			},
		},
		...option,
	};
}

const colors = ['#5470C6', '#91CC75', '#EE6666', '#1E90FF', '#00FA9A', '#3CB371', '#FFF8DC', '#FAF0E6', '#CD5C5C', '#DC143C', '#FF1493', '#4B0082', '#9932CC', '#BA55D3', '#6495ED', '#B0C4DE'];
const lineECharts = (param) => {
	const line = lineOption;
	const legends = param.paramList.map((item: any) => item.paramName + ` (${item.unit})`);
	let xData = [];
	let series = [];
	let yData = [];
	param.paramList.forEach((item: any, index) => {
		item.valueList.forEach((p: any) => {
			if (xData.every((t) => t !== p.x)) {
				xData.push(p.x);
			}
		});
		let indexSub = index % 2;
		let colorIndex = index % 16;
		let indexdiv = index / 2;
		let offsetNum = indexdiv * 60;
		yData.push({
			type: 'value',
			name: item.paramName,
			position: (indexSub == 0 ? 'left' : 'right'),
			offset: offsetNum,
			alignTicks: true,
			axisLine: {
				show: true,
				lineStyle: {
					color: colors[index]
				}
			},
			axisLabel: {
				show: true,
				formatter: '{value} ' + ((item.unit != null && item.unit != '') ? item.unit : '')
			}
		})
		series.push({
			name: item.paramName + ` (${item.unit})`,
			smooth: param.style.line.smooth,
			type: 'line',
			yAxisIndex: index,
			data: item.valueList.map((p: any) => p.y),
		});
	});

	line.dataZoom[0].show = param.style.xDateLine;
	line.dataZoom[1].disabled = param.style.line.disabled;
	line.dataZoom[2].show = param.style.yDateLine;
	line.legend.data = legends;
	line.xAxis.data = xData.filter((i) => i);
	line.yAxis = yData;
	line.series = series;
	return line;

};

const pieECharts = (param) => {
	const pie = pieOption;
	pie.series[0].data = param.paramList.map((item: { valueList: any[]; paramName: any }) => {
		let total: any = 0;
		item.valueList.forEach((item: any) => {
			total = total + Number(item.value)
			total = unifyNumber(total)
		});
		return {
			name: item.paramName,
			value: total,
		};
	});

	pie.series[0].center = [param.style.pie.centerLeft + '%', param.style.pie.centerTop + '%'];
	pie.series[0].radius = [param.style.pie.innerCircle + '%', param.style.pie.outerCircle + '%'];

	return pie;
};

const barECharts = (param) => {
	const bar = barOption;
	const legends = param.paramList.map((item: any) => item.paramName + ` (${item.unit})`);

	let xData = [];
	let series = [];
	let yData = [];
	param.paramList.forEach((item: any, index) => {
		item.valueList.forEach((p: any) => {
			if (xData.every((t) => t !== p.x)) {
				xData.push(p.x);
			}
		});
		let indexSub = index % 2;
		let colorIndex = index % 16;
		let indexdiv = index / 2;
		let offsetNum = indexdiv * 60
		yData.push({
			type: 'value',
			name: item.paramName,
			position: (indexSub == 0 ? 'left' : 'right'),
			offset: offsetNum,
			alignTicks: true,
			axisLine: {
				show: true,
				lineStyle: {
					color: colors[index]
				}
			},
			axisLabel: {
				show: true,
				formatter: '{value} ' + ((item.unit != null && item.unit != '') ? item.unit : '')
			}
		})
		series.push({
			name: item.paramName + ` (${item.unit})`,
			type: 'bar',
			barGap: param.style.bar.barGap + '%',
			barWidth: param.style.bar.barWidth,
			yAxisIndex: index,
			emphasis: {
				focus: 'series',
			},
			data: item.valueList.map((p: { y: any }) => p.y),
		});
	});

	bar.dataZoom[0].show = param.style.xDateLine;
	bar.dataZoom[1].disabled = param.style.bar.disabled;
	bar.dataZoom[2].show = param.style.yDateLine;
	bar.legend.data = legends;
	bar.xAxis.data = xData.filter((i) => i);
	bar.yAxis = yData;
	bar.series = series;
	return bar;

};

onLoad((options) => {
	console.log(options.params)
	const params = JSON.parse(options.params);
	const id = params.id;
	init({
		id: id,
	});
});
const checkPost = () => {
	// 获取用户的岗位 和签字
	// getPersonByPersonCode
	const userInfos = userStore.userInfos;
	const cusPerson = userInfos.user.username;
	getPersonByPersonCode({
		personCode: cusPerson,
	}).then((res) => {
		if (!res.data) return;
		const sign = res.data.signature;
		signature.value = sign;
		const hrPersonDeptList = res.data.hrPersonDeptList;
		const postNameList = hrPersonDeptList.map((item) => item.postName); // 岗位列表
		// 判断是否有总工 、 副总工 、技术负责人
		const _isChiefEngineer = postNameList.find(
			(item) => item && item.indexOf('副总工') < 0 && item.indexOf('总工') >= 0,
		);
		const _isDeputyChiefEngineer = postNameList.find((item) => item && item.indexOf('副总工') >= 0);

		const _isLaboratoryLeader = postNameList.find(
			(item) => item && item.indexOf('实验室负责人') >= 0,
		);
		isChiefEngineer.value = _isChiefEngineer;
		isDeputyChiefEngineer.value = _isDeputyChiefEngineer;

		if (_isChiefEngineer || _isDeputyChiefEngineer) {
			showSign.value = true;
		} else {
			showSign.value = false;
		}
		userInfo.value = res.data;
	});
};

const sign = () => {
	// uni.navigateTo({
	//   url: '/pages/pm/requirement/sign',
	// });

	// 判断签字
	const userInfos = userStore.userInfos;
	const cusPerson = userInfos.user.username;
	getPersonByPersonCode({
		personCode: cusPerson,
	}).then((res) => {
		const sign = res.data.signature;
		signature.value = sign;
		if (sign) {
			showAction.value = true;
		} else {
			signReset();
			// uni.navigateTo({
			//   url: '/pages/pm/requirement/autograph',
			// });
		}
	});

	// uni.navigateTo({
	//   url: '/pages/pm/requirement/autograph',
	// });
};

onPullDownRefresh(() => {
	init({
		id: form.id,
	});
});

const goBack = () => {
	uni.navigateBack();
};

const preview = (url) => {
	if (!url) return;
	uni.previewImage({
		urls: [url],
	});
};

const closeSign = () => {
	showAction.value = false;
	uni.$off('pm-requirement-sign');
};

const signHanle = (sign) => {
	const userInfos: any = userInfo.value;
	// 判断岗位
	// const _isChiefEngineer = isChiefEngineer.value;
	// const _isDeputyChiefEngineer = isDeputyChiefEngineer.value;
	// const _isLaboratoryLeader = isLaboratoryLeader.value;
	const params = {
		id: form.id,
		signName: userInfos.personName,
		signUrl: sign,
	};

	// if (!_isChiefEngineer && !_isDeputyChiefEngineer && !_isLaboratoryLeader) {
	//   uni.showToast({
	//     title: '只有总工和副总工和技术负责人才能签字',
	//     icon: 'none',
	//   });
	//   return;
	// }

	// if (_isChiefEngineer) {
	//   // params['chiefEngineer'] = userInfos.id;
	//   params['chiefEngineer'] = userInfos.personCode;
	//   params['signName'] = userInfos.personName;
	//   params['chiefEngineerPost'] = _isChiefEngineer;
	//   params['signUrl'] = sign;
	// } else if (_isDeputyChiefEngineer) {
	//   params['deputyChiefEngineer'] = userInfos.personCode;
	//   params['signName'] = userInfos.personName;
	//   params['deputyChiefEngineerPost'] = _isDeputyChiefEngineer;
	//   params['signUrl'] = sign;
	// } else if (_isLaboratoryLeader) {
	//   params['laboratoryLeader'] = userInfos.personCode;
	//   params['signName'] = userInfos.personName;
	//   params['laboratoryLeaderPost'] = _isLaboratoryLeader;
	//   params['signUrl'] = sign;
	// }
	updateByIdEvery(params)
		.then((res) => {
			uni.showToast({
				title: '签字成功',
			});

			// setTimeout(() => {
			//   uni.navigateBack();
			// }, 500);

			// 更新签字
			if (!signature.value) {
				uploadSignature({
					id: userInfos.id,
					signature: sign,
				});
			}
			showAction.value = false;
			// 刷新页面
			init({
				id: form.id,
			});
		})
		.finally(() => {
			// uni.$off('pm-requirement-sign');
		});
};


const getBjReportResultList = (id) => {
	if (!id) return
	reportInfo('qcMiddleReport', { id })
		.then((res) => {
			if (res.code === 0) {
				if (res.data.qcMiddleReportsList) {
					reportResultList.value = []
					res.data.qcMiddleReportsList.map((item) => {
						item.itemDTOS &&
							item.itemDTOS.map((p) => {
								if (!res.data.resultFlag) {
									p.standardValuePm = '';
								}

								reportResultList.value.push(p);
							});
					});
				}
			}
		})
	// getQcMiddleReport(id)
	// 	.then((res) => {
	// 		if (res.code === 0) {
	// 			if (res.data.qcMiddleReportsList) {
	// 				res.data.qcMiddleReportsList.map(item => {
	// 					item.itemDTOS && item.itemDTOS.map(p => {
	// 						if (!res.data.resultFlag) {
	// 							p.standardValuePm = ""
	// 						}
	// 						reportResultList.value.push(p)
	// 					})
	// 				})
	// 			}

	// 		}
	// 	})
}

const signThis = () => {
	const sign = signature.value;
	signHanle(sign);
};

const signReset = () => {
	uni.$on('pm-requirement-sign', (e) => {
		console.log('sign', e);
		signHanle(e);
	});
	uni.navigateTo({
		url: '/pages/pm/requirement/autograph',
	});
};

const isImage = (url: string) => {
	if (!url) return '';
	const suffix = url.replace(/.*\./, '') || url;
	return ['jpg', 'jpeg', 'png', 'gif', 'svg', 'JPG', 'JPEG', 'PNG', 'GIF', 'SVG', 'WebP'].includes(suffix);
};

const previewFile = (url) => {
	if (!url) return
	if (isImage(url)) {
		preview(url)
	} else {
		previewWeb(url)
	}
}

const previewImg = (url) => {
	if (!url) return;
	uni.previewImage({
		urls: [url],
	});
};

const previewFileHandle = (file) => {
	uni.navigateTo({
		url: '/pages/pm/preview-online?url=' + file,
	});
};

const previewWeb = (url) => {
	uni.navigateTo({
		url: '/pages/pm/preview-online?url=' + url + '&isWeb=1',
	});
};

const handleSave = async function () {
	uni.showLoading({
		mask: true,
	});
	try {
		const res = await putObj(form);
		if (res.code === 0) {
			uni.showToast({
				mask: true,
				title: `保存成功`,
				icon: 'none',
			});

			init({
				id: form.id,
			});
		}
	} catch (err) {
		uni.hideLoading();
	}
};
onUnload(() => {
	uni.hideLoading()
})
</script>

<style lang="scss" scoped>
@import "../experiment/components/table.scss";

.block .content {
	padding: 0 !important;
}

.card-detail {
	padding: 0 !important;
}

.wd-cell {
	padding-left: 0 !important;
}

.wd-card__title {
	border-left: 4px solid #2e5cf6 !important;
}

.pm-table {
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	padding: 0 30rpx;

	.pm-title {
		box-sizing: border-box;
		padding-left: 20rpx;
		margin: 40rpx 0;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		border-left: 8rpx solid #2e5cf6;
		border-radius: 4rpx;
	}

	.pm-row {
		display: flex;
		min-height: 60rpx;
		border-bottom: 1px solid #f6f0f0;

		.pm-label {
			display: flex;
			align-items: center;
			width: 20%;
			font-size: 26rpx;
			color: #979494;
		}

		.pm-value {
			display: flex;
			flex: 1;
			align-items: center;
			font-size: 26rpx;
			color: #333;
		}
	}
}

.sign-main {
	// display: flex;
	// align-items: center;
	// justify-content: center;
	// width: 100%;
	// margin: 20rpx 0;
	position: fixed;
	right: 0rpx;
	bottom: 40rpx;
	width: 160rpx;
	height: 80rpx;
	line-height: 80rpx;
	color: white;
	text-align: center;
	background-color: rgb(77 128 240);

	// border-radius: 50%;
	border-top-left-radius: 40rpx;
	border-bottom-left-radius: 40rpx;
}

:deep(.label) {
	width: 160rpx !important;
}

.result-tag {
	padding: 6rpx 14rpx;
	margin: 2rpx 0;
	font-size: 24rpx;
	color: white;
	background-color: #87d068;
	border-radius: 4rpx;
}

.sign-main-show {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;

	.sign-main-show-title {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 80rpx;
		margin-bottom: 20rpx;
		font-size: 30rpx;
		font-weight: bold;
		color: #818181;
		border-bottom: 1px solid #e3e3e3;
	}

	.sign-main-show-line {
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 90%;
		padding: 20rpx;
		margin-bottom: 20rpx;
		border: 4rpx solid #d0dbff;
		border-radius: 10rpx;
	}

	.sign-main-show-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 80rpx;
		border-top: 1px solid #e3e3e3;
	}
}

.info-list {
	display: flex;
	flex-direction: column;
	width: 100%;
}

.info-list-main {
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	width: 100%;
	padding: 10rpx;
	margin: 10rpx 0;
	border: 1px solid #e3e3e3;
	border-radius: 8rpx;

	.info-list-row {
		display: flex;
		width: 100%;

		.info-list-label {
			width: 150rpx;
			font-size: 28rpx;
			color: #808080;
		}

		.info-list-value {
			flex: 1;
			width: 0;
		}
	}
}

.chart-container {
	padding-top: 24rpx;
}


.diabledStyle {
	:deep() {

		.wd-picker__value,
		.wd-textarea__inner {
			color: #262626 !important;
		}

		.wd-picker__cell {
			padding: 0;
		}
	}
}

.viewTable {
	flex: auto;

	:deep() {
		.content {
			width: calc(100% - 80px);
		}
	}
}

.craft-row-img {
	height: 80rpx;
	width: 80rpx;
}

.flow-btn-fixed {
	width: 100%;
	background-color: white;
}

.btn_group {
	display: flex;
	justify-content: space-between;

	.btn {
		display: flex;

		// width: 49%;
		flex: 1;
		align-items: center;
		justify-content: center;
		min-height: 40px;
		padding: 10rpx 0;
		font-size: 0.8rem;
		color: black;
		background-color: #dbecff !important;
		border-left: 1px solid #f7f7f7;
		border-radius: 6rpx;

	}

	.btn-icon {
		width: 1rem;
		height: 1rem;
		margin-right: 8rpx;
	}

	.danger {
		background-color: #f56c6c;
	}

	.primary {
		background-color: #409eff;
	}


}

.viewLabel {
	position: relative;
	flex: 1;
	min-width: 16.875rem;
	padding: 0.5625rem 0;
	margin: 0 0.75rem;
	flex-shrink: 0;
	width: 3.75rem;
	font-size: 0.8125rem;
	line-height: 1;
	color: #666;
}

.viewLabel~.table-container {
	margin: 0 0.75rem;
}

:deep() {
	.wd-textarea {
		&::after {
			display: none !important;
		}
	}
}


.exportModel {
	width: 100%;
	margin-top: 10rpx;
	font-size: 28rpx;
	color: #409eff;
	text-align: center;
}


.th-table {
	max-height: 500px;

	.sticky_top {
		position: sticky;
		top: 0;
		z-index: 9;

		th::before {
			content: '';
			width: 100%;
			height: 1px;
			background: #dedede;
			position: absolute;
			top: -1px;
			left: 0;
		}
	}
}
</style>